<script setup lang="tsx">
import { computed, ref } from 'vue';
import { $t } from '@/locales';
import type { ApiStateInput, ApiSysLogOut, ApiSysLogQuery } from '@/api-services';
import { feature, getAPI } from '@/axios-utils';
import { fetchTableQuery, useNetoTable, useTableOperate, useTableScroll } from '@/hooks/common/neto-table';
import { queryDone } from '@/utils/api';
import { UserApi } from '@/api-services/apis/user-api';
import OperateModal from './modules/operate-modal.vue';
import Search from './modules/search.vue';
import { SyslogApi } from '@/api-services/apis/syslog-api';
import { ElButton, ElPopconfirm, ElTag } from 'element-plus';


const { tableWrapperRef, scrollConfig } = useTableScroll();

// 定义 apiFunc 为一个函数，接受参数并返回 Promise
const apiFunc = (params: ApiSysLogQuery) =>
  fetchTableQuery<ApiSysLogQuery, ApiSysLogOut>(params, (internalParams: ApiSysLogQuery) =>
    getAPI(SyslogApi).getList(internalParams)
  );

const loadingStates = ref<Record<string, boolean>>({});

const {
  columns,
  columnChecks,
  data,
  tableSize,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useNetoTable({
  apiFn: apiFunc,
  size: 'small',
  // apiFn:fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList),
  // apiFn: fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList.bind(getAPI(ApiuserserviceApi))),
  apiParams: {
    pageIndex: 1,
    pageSize: 10,
    keyWords: '',
    logType: undefined,
    isSuccess: undefined,
    startDate: undefined,
    endDate: undefined
  },
  columns: () => [

    { type: 'selection', width: 48 },
    {
      prop: 'id',
      //dataIndex: 'id',
      label: 'id',
      minWidth: 130
    },
    {
      prop: 'creationTime',
      //dataIndex: 'creationTime',
      //创建时间
      label: $t('common.creationTime'),
      align: 'center',
      minWidth: 150
    },
    {
      prop: 'logType',
      //dataIndex: 'logType',
      //日志类型
      label: $t('page.sysLog.logType'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        switch (record.logType) {
          case 0:
            return <ElTag type="success">{$t('page.sysLog.logTypeEnum.systemLog')}</ElTag>
          case 1001:
            return <ElTag type="warning">{$t('page.sysLog.logTypeEnum.operationLog')}</ElTag>
          default: return '';
        }
      },
    },
    {
      prop: 'isSuccess',
      //dataIndex: 'isSuccess',
      //是否执行成功
      label: $t('page.sysLog.isSuccess'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        switch (record.isSuccess) {
          case true:
            return <ElTag type="success">{$t('common.yesOrNo.yes')}</ElTag>;
          case false:
            return <ElTag type="danger">{$t('common.yesOrNo.no')}</ElTag>;
          default:
            return '';
        }
      },
    },
    {
      prop: 'ip',
      //dataIndex: 'ip',
      label: 'IP',
      align: 'center',
      minWidth: 100,
    },
    {
      prop: 'requestUrl',
      //dataIndex: 'requestUrl',
      //请求地址
      label: $t('page.sysLog.requestUrl'),
      align: 'center',
      minWidth: 300,
    },
    // {
    //   prop: 'message',
    //   //dataIndex: 'message',
    //   //具体消息
    //   label: $t('page.sysLog.message'),
    //   align: 'center',
    //   hide: true,
    //   minWidth: 500,
    // },
    // {
    //   prop: 'exception',
    //   //dataIndex: 'exception',
    //   //异常信息
    //   label: $t('page.sysLog.exception'),
    //   align: 'center',
    //   hide: true,
    //   minWidth: 500,
    // },
    // {
    //   prop: 'logContent',
    //   //dataIndex: 'logContent',
    //   //日志内容
    //   label: $t('page.sysLog.logContent'),
    //   align: 'center',
    //   hide: true,
    //   minWidth: 500,
    // },

    {
      prop: 'elapsedTime',
      //dataIndex: 'elapsedTime',
      //耗时
      label: $t('page.sysLog.elapsedTime'),
      align: 'center',
      minWidth: 100,
    },
    {
      prop: 'index',
      label: $t('common.operate'),
      align: 'center',
      minWidth: 230,
      fixed: 'right',
      formatter: record => {
        return (<div class="flex-center gap-8px">
          <ElButton type="primary" plain size="small" onClick={() => edit(record.id!)}>
            {$t('common.detail')}
          </ElButton>
          <ElPopconfirm onConfirm={() => handleDelete(record.id!)} title={$t('common.confirmDelete')}>
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>)
      }

    }
  ]
});

const {
  isVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted

} = useTableOperate(data, getData);
const edit = (id: number) => {
  // console.log(id);
  handleEdit(id);
};
const handleDelete = async (id: number) => {

  // 提交请求
  const [err, res] = await feature(getAPI(SyslogApi).batchDelete(id.toString()));

  queryDone(err, async () => {
    if (res?.data.data) {
      onDeleted();
    } else {
      // 失败
      window.$message?.error($t('common.failed'));
    }
  });
};
const handleBatchDeleted = async () => {
  const ids = checkedRowKeys.value;
  if (!ids) {
    return;
  }
  // 提交请求
  const [err, res] = await feature(getAPI(SyslogApi).batchDelete(ids.join(',')));

  queryDone(err, async () => {
    if (res?.data.data) {
      onBatchDeleted();
    } else {
      // 失败
      window.$message?.error($t('common.failed'));
    }
  });
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <!-- 系统日志 -->
    <Search v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage"></Search>

    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.sysLog.logTypeEnum.systemLog') }}</p>
          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            v-model:size="tableSize" :show-table-size="true" :loading="loading" :show-add="false"
            @delete="handleBatchDeleted" @refresh="getData" />
        </div>
      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="id"
          @selection-change="checkedRowKeys = $event">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
      </div>
      <div class="mt-20px flex justify-end">
        <ElPagination v-if="mobilePagination.total" layout="total,prev,pager,next,sizes" v-bind="mobilePagination"
          v-model:current-page="mobilePagination.currentPage" v-model:page-size="mobilePagination.pageSize" />
      </div>
      <OperateModal v-model:visible="isVisible" :operate-type="operateType" :row-data="editingData"
        @submitted="getDataByPage" />
    </ElCard>
  </div>
</template>

<style scoped></style>
